<?php


namespace App\Http\Controllers;

use App\Services\AttachmentService;
use App\Services\CommonService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class AttachmentController extends Controller
{
    public $attachmentService;

    public function __construct(AttachmentService $attachmentService)
    {
        parent::__construct();
        $this->attachmentService = $attachmentService;
    }

    /**
     * 单文件上传 阿里云OSS 或 本地（图片，PDF）
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function upload(Request $request)
    {
        try {
            $saveType = $request->input('save_type', 'oss');
            $file     = $request->file('file');
            $result   = $this->attachmentService->upload($file, $saveType);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
        CommonService::addActionLog('文件上传', "源文件名:{$result['origin_name']},地址:{{$result['file']}}");

        return $this->success($result, '文件加载完毕');
    }

    /**
     * OSS文件下载，返回的 $signedUrl 浏览器访问直接执行下载
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function download(Request $request)
    {
        $fileUrl = $request->input('file_url');
        $newName = $request->input('origin_name');
        if (!$fileUrl || !$newName) {
            return $this->error('参数错误！', 400);
        }
        if (!$signedUrl = $this->attachmentService->download($fileUrl, $newName)) {
            return $this->error('下载失败~');
        };

        return $this->success($signedUrl, '下载成功！');
    }

}
